package com.changzhi.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.changzhi.common.annotation.Verify;
import com.changzhi.common.constans.Constants;
import com.changzhi.common.constans.RedisConstans;
import com.changzhi.common.util.Result;
import com.changzhi.ldyl.model.ChatChannel;
import com.changzhi.ldyl.model.User;
import com.changzhi.ldyl.model.UserGift;
import com.changzhi.ldyl.model.dto.YearDto;
import com.changzhi.ldyl.model.vo.PageVo;
import com.changzhi.ldyl.model.vo.UserVo;
import com.changzhi.ldyl.model.vo.YearRankingVo;
import com.changzhi.mapper.UserGiftMapper;
import com.changzhi.service.ChatChannelService;
import com.changzhi.service.UserService;
import com.changzhi.service.YearService;
import com.changzhi.util.CommonUtil;
import com.changzhi.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Description:年度活动
 * @author: 小落
 * @date: 2020年11月02日
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("year")
public class YearController {

	@Autowired
	private YearService yearService;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private UserGiftMapper userGiftMapper;
	@Autowired
	private UserService userService;
	@Autowired
	private ChatChannelService chatChannelService;


	/**
	 * 获取内存数据
	 * @return
	 */
	@Verify(login = false)
	@PostMapping("getMemoryData")
	public Result getMemoryData(){
		return Result.success(yearService.getMemoryData());
	}

	/**
	 * pk列表
	 * @return
	 */
	@Verify(login = false)
	@PostMapping("pkList")
	public Result pkList(@RequestBody @Validated YearDto yearDto){
		long start = System.currentTimeMillis();
		Object data = yearService.pkList(yearDto);
		log.info("methodName:pkList,耗时={}", System.currentTimeMillis() - start);
		return Result.success(data);
	}


	/**
	 * 年度明厅
	 * @return
	 */
	@Verify(login = false)
	@PostMapping("channelRankings")
	public Result channelRankings(@RequestBody @Validated YearDto yearDto){
		long start = System.currentTimeMillis();
		Object data = yearService.getChannelRankings(yearDto);
		log.info("methodName:channelRankings,耗时={}", System.currentTimeMillis() - start);
		return Result.success(data);
	}


	/**
	 * 年度之星
	 * @return
	 */
	@Verify
	@PostMapping("starRankings")
	public Result starRankings(@RequestBody @Validated YearDto yearDto){
		long start = System.currentTimeMillis();
		Object data = yearService.getStarRankings(yearDto);
		log.info("methodName:starRankings,耗时={}", System.currentTimeMillis() - start);
		return Result.success(data);
	}

	/**
	 * 王牌公会
	 * @return
	 */
	@Verify(login = false)
	@PostMapping("externalRankings")
	public Result externalRankings(@RequestBody @Validated YearDto yearDto){
		long start = System.currentTimeMillis();
		PageVo<Map<String,Object>> pageVo = yearService.getExternalRankings(yearDto);
		log.info("methodName:externalRankings,耗时={}", System.currentTimeMillis() - start);
		return Result.success(pageVo);
	}

	/**
	 * 年度神豪
	 * @return
	 */
	@Verify
	@PostMapping("bossRankings")
	public Result bossRankings(@RequestBody @Validated YearDto yearDto){
		long start = System.currentTimeMillis();
		Map<String,Object> map = yearService.getBossRankings(yearDto);
		log.info("methodName:bossRankings,耗时={}", System.currentTimeMillis() - start);
		return Result.success(map);
	}

	/**
	 * 获取锁状态
	 * @return
	 */
	@Verify
	@PostMapping("channelLockStatus")
	public Result channelLockStatus(@RequestBody @Validated YearDto yearDto){
		long start = System.currentTimeMillis();
		Map<String,Object> map = yearService.getChannelLockStatus(yearDto);
		log.info("methodName:channelLockStatus,耗时={}", System.currentTimeMillis() - start);
		return Result.success(map);
	}

	/**
	 * pk最终前三名
	 * @return
	 */
	@Verify(login = false)
	@PostMapping("topChannelList")
	public Result topChannelList(@RequestBody @Validated YearDto yearDto){
		long start = System.currentTimeMillis();
		List<YearRankingVo> list = yearService.getTopChannelList();
		log.info("methodName:topChannelList,耗时={}", System.currentTimeMillis() - start);
		return Result.success(list);
	}


	/**
	 * 年度之星前十名
	 * @return
	 */
	@Verify(login = false)
	@PostMapping("topStarList")
	public Result topStarList(@RequestBody @Validated YearDto yearDto){
		long start = System.currentTimeMillis();
		Object data = yearService.topStarList(yearDto);
		log.info("methodName:topStarList,耗时={}", System.currentTimeMillis() - start);
		return Result.success(data);
	}

	/**
	 * 年度神豪前十名
	 * @return
	 */
	@Verify(login = false)
	@PostMapping("topBossList")
	public Result topBossListt(@RequestBody @Validated YearDto yearDto){
		long start = System.currentTimeMillis();
		Object data = yearService.topBossList(yearDto);
		log.info("methodName:topBossList,耗时={}", System.currentTimeMillis() - start);
		return Result.success(data);
	}

	/**
	 * 年度公会前三名
	 * @return
	 */
	@Verify(login = false)
	@PostMapping("topExternalList")
	public Result topExternalList(@RequestBody @Validated YearDto yearDto){
		long start = System.currentTimeMillis();
		Object data = yearService.topExternalList(yearDto);
		log.info("methodName:topExternalList,耗时={}", System.currentTimeMillis() - start);
		return Result.success(data);
	}


	/**
	 * 初始化对战pk厅
	 * @return
	 */
	@PostMapping("initPkList")
	public Result initPkList(@RequestBody Map<String,Object> params){
		CommonUtil.checkPwd((String) params.get("pwd"));
		yearService.initPkList();
		return Result.success();
	}

	/**
	 * 手动初始化某个厅或所有厅（未pk前）
	 * @return
	 */
	@PostMapping("updatePkList")
	public Object updatePkList(@RequestBody Map<String,Object> params){
		CommonUtil.checkPwd((String) params.get("pwd"));
		String c = (String) params.get("c");
		String type = (String) params.get("type");

		if("1".equals(c)){//单个未pk前
			String oldChannelId = getChatChannelInfo(Integer.valueOf((String) params.get("oldAccountId"))).getChannelId();
			String oldTargetChannelId = getChatChannelInfo(Integer.valueOf((String) params.get("oldTargetAccountId"))).getChannelId();
			String oldItem = CommonUtil
					.getGroupId(oldChannelId, oldTargetChannelId);
			redisUtil.hdel(RedisConstans.YEAR_CHANNEL_PK + "_" + type,oldItem);
			List<Map<String,Object>> data = (List<Map<String, Object>>) params.get("data");
			yearService.updatePkList(type,data);
		} else if("2".equals(c)){//所有未pk前
			List<Map<String,Object>> data = (List<Map<String, Object>>) params.get("data");
			redisUtil.del(RedisConstans.YEAR_CHANNEL_PK + "_" + type);
			yearService.updatePkList(type,data);
		} else if("3".equals(c)){//所有已pk

		}
		return Result.success();
	}

	/**
	 * 修正主播值
	 * @return
	 */
	@PostMapping("checkStarValue1")
	public Object checkStarValue1(@RequestBody Map<String,Object> map) {
		CommonUtil.checkPwd((String) map.get("pwd"));
		List<String> userIdList = redisUtil.get(RedisConstans.YEAR_STAR_ID_1);
		if(CollectionUtils.isEmpty(userIdList)){
			return "空";
		}
		log.warn("=========1:{}", JSON.toJSONString(userIdList));
		String key = RedisConstans.YEAR_STAR + "_1";
		for (String userId : userIdList) {
			// 获取合同包下所有合同的总金额之和
			QueryWrapper<UserGift> wrapper = new QueryWrapper<>();
			wrapper.lambda().eq(UserGift::getTargetId, userId).ge(UserGift::getCreateTime,"2020-12-08 00:00:00").le(UserGift::getCreateTime,"2020-12-09 23:59:59");
			wrapper.select("ifnull(sum(total_gift_value)*10,0) as total ");
			List<Map<String, Object>> list = userGiftMapper.selectMaps(wrapper);
			Integer value = Integer.valueOf(String.valueOf(list.get(0).get("total")));

			UserVo userVo = (UserVo)  redisUtil.hget(key, userId);
			if(userVo != null){
				log.warn("=========旧:useId={},data={}", userId,JSON.toJSONString(userVo));
				userVo.setValue(value);
				log.warn("=========3:useId={},value={},data={}", userId,value,JSON.toJSONString(userVo));
				redisUtil.hset(key, userId, userVo, RedisConstans.ONE_MONTH);
			} else {
				User user = userService.getUser(userId);
				if (user == null) {
					continue;
				}
				userVo = new UserVo();
				userVo.setUserId(user.getUserId())
						.setAccountId(user.getAccountId())
						.setAvatarUrl(StringUtils.isNotBlank(user.getAvatarUrl()) ? user.getAvatarUrl() : Constants.DEFAULT_AVATAR)
						.setNickname(user.getNickname())
						.setValue(value);
				log.warn("=========4:useId={},value={},data={}", userId,value,JSON.toJSONString(userVo));
				redisUtil.hset(key, user.getUserId(), userVo, RedisConstans.ONE_MONTH);

			}
		}
		return "okok";
	}

	/**
	 * 修正频道值
	 * @return
	 */
	@PostMapping("checkChannelValue")
	public Object checkChannelValue(@RequestBody Map<String,Object> map) {
		CommonUtil.checkPwd((String) map.get("pwd"));

		String key = RedisConstans.YEAR_CHANNEL + "_0";
		if(StringUtils.isNotBlank((String) map.get("channelId"))){
			String channelId = (String) map.get("channelId");
			YearRankingVo yearRankingVo = (YearRankingVo) redisUtil.hget(key, channelId);
			log.warn("=========4:channelId={},data={}", channelId,JSON.toJSONString(yearRankingVo));
			if(yearRankingVo != null){
				// 获取合同包下所有合同的总金额之和
				QueryWrapper<UserGift> wrapper = new QueryWrapper<>();
				wrapper.lambda().eq(UserGift::getChannelId, channelId).ge(UserGift::getCreateTime,"2020-11-30 00:00:00");
				wrapper.select("ifnull(sum(total_gift_value)*10,0) as total ");
				List<Map<String, Object>> list = userGiftMapper.selectMaps(wrapper);
				Long value = Long.valueOf(String.valueOf(list.get(0).get("total")));
				yearRankingVo.setValue(value);
				log.warn("=========5:channelId={},value={},data={}", channelId,value,JSON.toJSONString(yearRankingVo));
				redisUtil.hset(key, channelId, yearRankingVo, RedisConstans.ONE_MONTH);
			}
		}else{
			Set<String> channelList = redisUtil.hKeys(key);
			log.warn("=========1:{}", JSON.toJSONString(channelList));
			for (String channelId : channelList) {
				YearRankingVo yearRankingVo = (YearRankingVo) redisUtil.hget(key, channelId);
				log.warn("=========2:channelId={},data={}", channelId,JSON.toJSONString(yearRankingVo));
				if(yearRankingVo != null){
					// 获取合同包下所有合同的总金额之和
					QueryWrapper<UserGift> wrapper = new QueryWrapper<>();
					wrapper.lambda().eq(UserGift::getChannelId, channelId).ge(UserGift::getCreateTime,"2020-11-30 00:00:00");
					wrapper.select("ifnull(sum(total_gift_value)*10,0) as total ");
					List<Map<String, Object>> list = userGiftMapper.selectMaps(wrapper);
					Long value = Long.valueOf(String.valueOf(list.get(0).get("total")));
					yearRankingVo.setValue(value);
					log.warn("=========3:channelId={},value={},data={}", channelId,value,JSON.toJSONString(yearRankingVo));
					redisUtil.hset(key, channelId, yearRankingVo, RedisConstans.ONE_MONTH);
				}
			}
		}
		return "okok";
	}

	/**
	 * 修正主播值
	 * @return
	 */
	@PostMapping("checkStarValue")
	public Object checkStarValue(@RequestBody Map<String,Object> map) {
		CommonUtil.checkPwd((String) map.get("pwd"));
		String key = RedisConstans.YEAR_STAR + "_0";
		if(StringUtils.isNotBlank((String) map.get("userId"))){
			String userId = (String) map.get("userId");
			UserVo userVo = (UserVo)  redisUtil.hget(key, userId);
			log.warn("=========4:channelId={},data={}", userId,JSON.toJSONString(userVo));
			if(userVo != null){
				// 获取合同包下所有合同的总金额之和
				QueryWrapper<UserGift> wrapper = new QueryWrapper<>();
				wrapper.lambda().eq(UserGift::getTargetId, userId).ge(UserGift::getCreateTime,"2020-12-05 00:00:00").le(UserGift::getCreateTime,"2020-12-07 23:59:59");
				wrapper.select("ifnull(sum(total_gift_value)*10,0) as total ");
				List<Map<String, Object>> list = userGiftMapper.selectMaps(wrapper);
				Integer value = Integer.valueOf(String.valueOf(list.get(0).get("total")));
				userVo.setValue(value);
				log.warn("=========5:userVo={},value={},data={}", userVo,value,JSON.toJSONString(userVo));
				redisUtil.hset(key, userId, userVo, RedisConstans.ONE_MONTH);
			}
		}else{
			Set<String> userIdList = redisUtil.hKeys(key);
			log.warn("=========1:{}", JSON.toJSONString(userIdList));
			for (String userId : userIdList) {
				UserVo userVo = (UserVo)  redisUtil.hget(key, userId);
				log.warn("=========2:useId={},data={}", userId,JSON.toJSONString(userVo));
				if(userVo != null){
					// 获取合同包下所有合同的总金额之和
					QueryWrapper<UserGift> wrapper = new QueryWrapper<>();
					wrapper.lambda().eq(UserGift::getTargetId, userId).ge(UserGift::getCreateTime,"2020-12-05 00:00:00").le(UserGift::getCreateTime,"2020-12-07 23:59:59");
					wrapper.select("ifnull(sum(total_gift_value)*10,0) as total ");
					List<Map<String, Object>> list = userGiftMapper.selectMaps(wrapper);
					Integer value = Integer.valueOf(String.valueOf(list.get(0).get("total")));
					userVo.setValue(value);
					log.warn("=========3:useId={},value={},data={}", userId,value,JSON.toJSONString(userVo));
					redisUtil.hset(key, userId, userVo, RedisConstans.ONE_MONTH);
				}
			}
		}
		return "okok";
	}

	private ChatChannel getChatChannelInfo(Integer accountId){
		QueryWrapper<ChatChannel> wrapper = new QueryWrapper<>();
		wrapper.lambda().eq(ChatChannel::getOwnerAccountid, accountId);
		wrapper.last("limit 1");
		return chatChannelService.getOne(wrapper);
	}

}
